<?php

namespace app\admin\controller;

use app\common\model;
use think\Controller;
use tpext\myadmin\admin\model\AdminUser;

class Index extends Controller
{
    protected $currentAdmin;

    protected function initialize()
    {
        $this->currentAdmin = AdminUser::current();
    }

    public function dashbord()
    {
        if ($this->currentAdmin['role_id'] == 1 || $this->currentAdmin['group_id'] == 1) {
            return $this->page1();
        } else {
            return $this->page2();
        }
    }

    private function page1()
    {
        $today_income = model\Transaction::where('pay_time', 'like', date('Y-m-d') . '%')->sum('total_amount');//今日收入
        $order_count = model\ShopOrder::where('pay_status', 1)->count();//订单数量（已支付）
        $goods_count = model\ShopGoods::where('on_sale', 1)->count();//上架商品数量
        $member_count = model\Member::where('status', 1)->count();//会员数量
        $order_wait = model\ShopOrder::where(['pay_status' => 1, 'shipping_status' => 0])->count();//待发货数量

        $days  = [];
        $new_members = [];
        $recharges = [];

        for ($i = 6; $i >= 0; $i -= 1) {
            $day = date('Y-m-d', strtotime("-$i days"));
            $days[] = $day;
            $where = [
                ['create_time', 'egt', $day . ' 00:00:00'],
                ['create_time', 'elt', $day . ' 23:59:59'],
            ];

            $new_members[] = model\Member::where($where)->count();
            $recharges[] = model\MemberRecharge::where($where)->where(['pay_status' => 1])->sum('account');

            // 添加交易记录图表
            $tran_where = [];
            $tran_where[] = ['pay_status', '=', 1];
//            $tran_where[] = ['order_type', '<>', 2];
            $start_time = $day . ' 00:00:00';
            $end_time = $day . ' 23:59:59';
            $trade_money[] = model\Transaction::where($tran_where)
                ->whereTime('create_time', 'between', [$start_time, $end_time])
                ->sum('total_amount');
        }
        $days = json_encode($days);
        $new_members = json_encode($new_members);
        $recharges = json_encode($recharges);
        $trade_money = json_encode($trade_money);

        /** 系统信息 */
        $sys_info['os'] = PHP_OS;
        $sys_info['zlib'] = function_exists('gzclose') ? '是' : '否';

        $sys_info['timezone'] = function_exists("date_default_timezone_get") ? date_default_timezone_get() : "no_timezone";
        $sys_info['curl'] = function_exists('curl_init') ? '是' : '否';
        $sys_info['web_server'] = request()->server('SERVER_SOFTWARE');
        $sys_info['user_agent'] = request()->server('HTTP_USER_AGENT');
        $sys_info['php_version'] = phpversion();
        $sys_info['ip'] = request()->ip();
        $sys_info['fileupload'] = @ini_get('upload_max_filesize') ?: '未知';
        $sys_info['sys_time'] = date('Y-m-d H:i:s', time());
        $sys_info['max_ex_time'] = @ini_get("max_execution_time") . 's';
        $sys_info['set_time_limit'] = function_exists("set_time_limit") ? true : false;
        $sys_info['domain'] = request()->host();
        $sys_info['memory_limit'] = ini_get('memory_limit');
        $mysqlinfo = db()->query('select VERSION() as version');
        $sys_info['mysql_version'] = json_encode($mysqlinfo);
        if (function_exists('gd_info')) {
            $gd = gd_info();
            $sys_info['gdinfo'] = $gd['GD Version'];
        } else {
            $sys_info['gdinfo'] = "未知";
        }

        $vars = compact('sys_info', 'today_income', 'order_count', 'goods_count', 'member_count', 'order_wait', 'days', 'new_members', 'recharges', 'trade_money');

        return $this->fetch('', $vars);
    }

    private function page2()
    {
        $today_income = model\Transaction::where('pay_time', 'like', date('Y-m-d') . '%')->sum('total_amount');//今日收入
        $order_count = model\ShopOrder::where('pay_status', 1)->count();//订单数量（已支付）
        $goods_count = model\ShopGoods::where('on_sale', 1)->count();//上架商品数量
        $member_count = model\Member::where('status', 1)->count();//会员数量
        $order_wait = model\ShopOrder::where(['pay_status' => 1, 'shipping_status' => 0])->count();//待发货数量

        $days  = [];
        $new_members = [];
        $recharges = [];

        for ($i = 6; $i >= 0; $i -= 1) {
            $day = date('Y-m-d', strtotime("-$i days"));
            $days[] = $day;
            $where = [
                ['create_time', 'egt', $day . ' 00:00:00'],
                ['create_time', 'elt', $day . ' 23:59:59'],
            ];

            $new_members[] = model\Member::where($where)->count();
            $recharges[] = model\MemberRecharge::where($where)->where(['pay_status' => 1])->sum('account');

            // 添加交易记录图表
            $tran_where = [];
            $tran_where[] = ['pay_status', '=', 1];
            $tran_where[] = ['order_type', '<>', 2];
            $start_time = $day . ' 00:00:00';
            $end_time = $day . ' 23:59:59';
            $trade_money[] = model\Transaction::where($tran_where)
                ->whereTime('create_time', 'between', [$start_time, $end_time])
                ->sum('total_amount');
        }
        $days = json_encode($days);
        $new_members = json_encode($new_members);
        $recharges = json_encode($recharges);
        $trade_money = json_encode($trade_money);

        $vars = compact('today_income', 'order_count', 'goods_count', 'member_count', 'order_wait', 'days', 'new_members', 'recharges', 'trade_money');

        return $this->fetch('dashbord2', $vars);
    }

    public function getMessageContent()
    {
        $customerservices = [];
        $msgCount = 0;

        $merchant_audit = [
            'name' => '商家入驻',
            'count' => 0,//model\boxpay\BoxpayShopApplyModel::where(['status' => 0, 'store_type' => 2])->count(),
            'url' => url('/admin/boxpay.boxpayshopapply/index')
        ];

        $store_audit = [
            'name' => '店铺申请',
            'count' => 0,//model\boxpay\BoxpayShopApplyModel::where(['status' => 0, 'store_type' => 2])->count(),
            'url' => url('/admin/boxpay.boxpayshopapply/index')
        ];

        $credential_audit = [
            'name' => '资质审核',
            'count' => 0,//model\StoreCredential::where('status', 0)->count(),
            'url' => url('/admin/merchant.credential/index')
        ];

        $product_audit = [
            'name' => '商品审核',
            'count' => 0,//model\merchant\ShopGoodsApplyModel::where(['status' => 0, 'shop_type' => 1])->count(),
            'url' => url('/admin/merchant.shopgoodsapply/index')
        ];

        $extract_cash_audit = [
            'name' => '提现审核',
            'count' => 0,//model\Withdrawal::where('state', 0)->count(),
            'url' => url('/admin/withdrawal/index')
        ];

        $credential_expired_reminder = [
            'name' => '资质过期',
            'count' => 0,//model\StoreCredential::where('status', 2)->count(),
            'url' => url('/admin/merchant.credential/index')
        ];

        $customerservices[] = '[' . $merchant_audit["name"] . ']<b style="color:red;">&nbsp;&nbsp;' . ($merchant_audit['count'] ?? '--') . '&nbsp;&nbsp;</b>条消息<a style="color:#333;margin-left:20px;" target="_blank" href="' . $merchant_audit["url"] . '"><i class="mdi mdi-message-text"></i>查看</a>';
        $customerservices[] = '[' . $store_audit["name"] . ']<b style="color:red;">&nbsp;&nbsp;' . ($store_audit['count'] ?? '--') . '&nbsp;&nbsp;</b>条消息<a style="color:#333;margin-left:20px;" target="_blank" href="' . $store_audit["url"] . '"><i class="mdi mdi-message-text"></i>查看</a>';
        $customerservices[] = '[' . $credential_audit["name"] . ']<b style="color:red;">&nbsp;&nbsp;' . ($credential_audit['count'] ?? '--') . '&nbsp;&nbsp;</b>条消息<a style="color:#333;margin-left:20px;" target="_blank" href="' . $credential_audit["url"] . '"><i class="mdi mdi-message-text"></i>查看</a>';
        $customerservices[] = '[' . $product_audit["name"] . ']<b style="color:red;">&nbsp;&nbsp;' . ($product_audit['count'] ?? '--') . '&nbsp;&nbsp;</b>条消息<a style="color:#333;margin-left:20px;" target="_blank" href="' . $product_audit["url"] . '"><i class="mdi mdi-message-text"></i>查看</a>';
        $customerservices[] = '[' . $extract_cash_audit["name"] . ']<b style="color:red;">&nbsp;&nbsp;' . ($extract_cash_audit['count'] ?? '--') . '&nbsp;&nbsp;</b>条消息<a style="color:#333;margin-left:20px;" target="_blank" href="' . $extract_cash_audit["url"] . '"><i class="mdi mdi-message-text"></i>查看</a>';
        $customerservices[] = '[' . $credential_expired_reminder["name"] . ']<b style="color:red;">&nbsp;&nbsp;' . ($credential_expired_reminder['count'] ?? '--') . '&nbsp;&nbsp;</b>条消息<a style="color:#333;margin-left:20px;" target="_blank" href="' . $credential_expired_reminder["url"] . '"><i class="mdi mdi-message-text"></i>查看</a>';

        $customerservices = implode('<br>', $customerservices);

        $msgCount = $merchant_audit['count'] + $store_audit['count'] + $credential_audit['count'] + $product_audit['count'] + $extract_cash_audit['count'] + $credential_expired_reminder['count'];

        return json([
            'code' => 1,
            'html' => $customerservices,
            'msg_count' => $msgCount,
        ]);
    }
}
